package com.otod.cd.doc.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.otod.base.exception.AppException;
import com.otod.base.service.BaseService;
import com.otod.cd.doc.constants.ShareConstant;
import com.otod.cd.doc.mapper.CdDocFileUsageMapper;
import com.otod.cd.doc.mapper.CdDocFolderMapper;
import com.otod.cd.doc.mapper.CdDocShareMapper;
import com.otod.cd.doc.vo.CdDocFolderVo;
import com.otod.commons.constants.CommonConstant;
import com.otod.commons.constants.LogConstant;
import com.otod.commons.filemanger.bo.FileBasicInfo;
import com.otod.commons.filemanger.service.IUploadSingleService;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.StringUtils;
import com.otod.pm.constants.PmConstant;
import com.otod.pm.prj.service.ProjectService;
import com.otod.pm.prj.vo.ProjectVo;

@Service
@Transactional(readOnly=true)
public class CdDocFileService extends BaseService implements IUploadSingleService {
	
	@Autowired
	CdDocFileUsageMapper cdDocFileUsageMapper;
	@Autowired
	CdDocFolderMapper cdDocFolderMapper;
	@Autowired
	CdDocShareMapper cdDocShareMapper;
	@Autowired
	ProjectService projectService;
	
	private static Logger logger = LoggerFactory.getLogger(CdDocFileService.class);
	/**
	 * 通过ID查询文件信息
	 * @param uuid
	 * @return
	 */
	public CdDocFolderVo getById(String uuid){
		if(StringUtils.isEmpty(uuid)){
			return null;
		}
		return cdDocFolderMapper.getById(uuid);
	}
	
	/**
	 * 新增
	 * @param CdDocFolderVo
	 * @return
	 */
	@Transactional
	public CdDocFolderVo insert(CdDocFolderVo cdDocFolderVo) {
		if(StringUtils.isEmpty(cdDocFolderVo.getUuid())){
			cdDocFolderVo.setUuid(super.getUUID());
		}
		
		cdDocFolderMapper.insert(cdDocFolderVo);
		//新增文件夹日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_ADD, cdDocFolderVo.getUuid(),"新增文件夹");
		return cdDocFolderVo;
	}
	
	/**
	 * 查询 信息
	 * @param param
	 * @return
	 */
	public List<CdDocFolderVo> queryForList(Map<String, Object> param){
		
		List<CdDocFolderVo> cdDocFolderVos = Lists.newArrayList();
		cdDocFolderVos = cdDocFolderMapper.queryForList(param);
		return cdDocFolderVos;
		
	}
	/**
	 * 通过父ID查询文件列表
	 * @param parentId	父ID
	 * @param isDel		是否删除
	 * @return
	 */
	public List<CdDocFolderVo> queryForListForParentId(String parentId,String isDel,String type,String createEmpNo){
		Map<String, Object> param = new HashMap<String, Object>();
		if(StringUtils.isEmpty(parentId)){
			param.put("searchForNullParentId", "true");
		}else{
			param.put("parentId", parentId);
		}
		
		
		param.put("isDel", isDel);
		param.put("createEmpNo",createEmpNo);
		param.put("type", type);
	
		return queryForList(param);
	}
	
	/**
	 * 通过父ID查询文件列表  共享文件查询
	 * @param parentId	父ID
	 * @param isDel		是否删除
	 * @return
	 */
	public List<CdDocFolderVo> queryForListForParentId(String parentId,String isDel){
		Map<String, Object> param = new HashMap<String, Object>();
	
		if(StringUtils.isEmpty(parentId)){
			param.put("searchForNullParentId", "true");
		}else{
			param.put("parentId", parentId);
		}
		param.put("isDel", isDel);
		
		return queryForList(param);
	}
	
	
	
	
	
	/**
	 * 添加文件夹
	 * @param map
	 * @throws AppException
	 */
	@Transactional
	public void saveFolder(CdDocFolderVo cdDocFolderVo) throws AppException{
		//查询是否有重复的名字
		List<CdDocFolderVo> cdDocFolderVos = Lists.newArrayList();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("folderName", cdDocFolderVo.getFolderName());
		map.put("parentId",cdDocFolderVo.getParentId());

		map.put("isDel", cdDocFolderVo.getIsDel());
		map.put("createEmpNo", cdDocFolderVo.getCreateEmpNo());
		map.put("type", cdDocFolderVo.getType());
		cdDocFolderVos = queryForList(map);
		if(Collections3.isNotEmpty(cdDocFolderVos)){
			throw new AppException("文件夹名字已经被使用");
		}
		CdDocFolderVo fatherCdDocFolderVo;
		if(!StringUtils.isEmpty(cdDocFolderVo.getParentId())){
			//通过父id查询上级目录的信息
			fatherCdDocFolderVo = getById(cdDocFolderVo.getParentId());
			//通过parentId查询数据folderPath 和 folderPathName 并且加上当前的folderPath 和folderPathName
			if(!StringUtils.isEmpty(fatherCdDocFolderVo.getFolderPath())){
				cdDocFolderVo.setFolderPath(fatherCdDocFolderVo.getFolderPath()+","+fatherCdDocFolderVo.getUuid());
				cdDocFolderVo.setFolderPathName(fatherCdDocFolderVo.getFolderPathName()+","+fatherCdDocFolderVo.getFolderName());
			}else{
				cdDocFolderVo.setFolderPath(fatherCdDocFolderVo.getUuid());
				cdDocFolderVo.setFolderPathName(fatherCdDocFolderVo.getFolderName());
			}
		}
		//调用添加文件夹得方法
		insert(cdDocFolderVo);
	}
	
	/**
	 * 删除文件 就是修改 is_del 还要修改删除源 yes or no
	 * @param split
	 */
	@Transactional
	public void deleteFolder(String[] uuids){
		Map<String, Object> map;
		for(String uuid : uuids){
			//通过uuid 
			map = new HashMap<String,Object>();
			map.put("uuid", uuid);
			map.put("isDel", CommonConstant.COMMON_YES);
			//设置删除源
			updateDelSource(uuid);
			updateSonFileDelSource(uuid);
			cdDocFolderMapper.updateOrDelete(map);
			//删除文件上传 日志
			super.invokeLogInsert( "400000000012", LogConstant.LOG_DELETE, uuid,"文件夹删除");
		}
	}
	/**
	 * 设置删除源   修改为CommonConstant.COMMON_YES 数据源
	 * @param uuid
	 */
	@Transactional
	public void updateDelSource(String uuid){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("uuid", uuid);
		map.put("delSource", CommonConstant.COMMON_YES);
		cdDocFolderMapper.update(map);
		//删除文件上传 日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_DELETE, uuid,"文件夹删除");
	}
	/**
	 * 设置不是删除源 修改为 CommonConstant.COMMON_NO 不是数据源
	 * @param uuid folderPath中是否包含uuid
	 */
	@Transactional
	public void updateSonFileDelSource(String uuid){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("uuid", uuid);
		map.put("delSource", CommonConstant.COMMON_NO);
		cdDocFolderMapper.updateSonFileDelSource(map);
		//日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_UPDATE, uuid,"文件夹还原");
	}
	/**
	 * 文件 文件夹重命名
	 * @param uuid
	 * @param folderName
	 */
	@Transactional
	public void updateFolderName(String parentId,String uuid,String folderName,String createEmpNo) throws AppException{
		
		//查询是否有重复的名字
		List<CdDocFolderVo> cdDocFolderVos = Lists.newArrayList();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("folderName", folderName);
		map.put("parentId",parentId);
		//由于有基础设置方法可以 isDel中设置了值的
		map.put("createEmpNo", createEmpNo);
		cdDocFolderVos = queryForList(map);
		if(Collections3.isNotEmpty(cdDocFolderVos)){
			throw new AppException("文件夹名字已经被使用");
		}
		
		map.remove("parentId");
		map.remove("createEmpNo");
		map.put("uuid", uuid);
		cdDocFolderMapper.update(map);
		
		map.clear();
		map.put("folderPathUuid", uuid);
		List<CdDocFolderVo> docFolderList =  cdDocFolderMapper.queryForList(map);
		
		for (CdDocFolderVo cdDocFolderVo : docFolderList) {
			String folderPath = cdDocFolderVo.getFolderPath();
			String[] folderPathString = folderPath.split(",");
			String folderPathName ="";
			int number = 0;
			for (String stringUuid : folderPathString) {
				CdDocFolderVo docFolder = cdDocFolderMapper.getById(stringUuid);
				if (number == 0 ) {
					folderPathName = docFolder.getFolderName();
				} else {
					folderPathName = folderPathName +"," + docFolder.getFolderName();
				}
				++number;
			}
			map.clear();
			map.put("uuid", cdDocFolderVo.getUuid());
			map.put("folderPathName", folderPathName);
			cdDocFolderMapper.update(map);
		}
		
		//日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_UPDATE, uuid,"文件夹重命名");

	}
	/**
	 * 修改成共享 
	 * @param uuid 文夹或者文件夹的名字
	 */
	@Transactional
	public void updateShared(String uuid){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("uuid", uuid);
		map.put("shared",CommonConstant.COMMON_YES);
	
		cdDocFolderMapper.update(map);
		//日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_UPDATE, uuid,"修改成共享");
	}
	
	
	/*************************************回收站处理service*******************************************/
	/**
	 * 查询回收站中的所有数据
	 * @return 返回删除文件夹得数据
	 */
	public List<CdDocFolderVo> queryForListRecycle(String delSource,String userNo){
		List<CdDocFolderVo> list = Lists.newArrayList();
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("delSource", delSource);
		map.put("createEmpNo", userNo);
		list = cdDocFolderMapper.queryForList(map);
		return list;
	}
	/**
	 * 恢复文件
	 * @param restoreNameFile
	 * @throws AppException 
	 */
	@Transactional
	public String updatedelSource(String uuid,String userNo) throws AppException{
		Map<String, Object> map;
		List<CdDocFolderVo> cdDocFolderVos;
		//主要是用于判断恢复了几个 

		String[] restoreUuid = uuid.split(",");
		CdDocFolderVo cdDocFolderVo;
		String repetitionFolderName ="";
		//通过uuid查询相关数据
		for (String resUuid : restoreUuid) {
			 cdDocFolderVo = getById(resUuid);
			 map = new HashMap<String, Object>();
			 map.put("folderName", cdDocFolderVo.getFolderName());
			 map.put("parentId", cdDocFolderVo.getParentId());
			 map.put("createEmpNo", cdDocFolderVo.getCreateEmpNo());
			 map.put("isDel", CommonConstant.COMMON_NO);
			 map.put("type", cdDocFolderVo.getType());
			 cdDocFolderVos = queryForList(map);
			 //名字没有重复的
			 if(Collections3.isEmpty(cdDocFolderVos)){
				 map.remove("folderName");
				 map.remove("parentId");
				 map.remove("createEmpNo");
				 
				 map.put("uuid",cdDocFolderVo.getUuid());
				 map.put("isDel", CommonConstant.COMMON_NO);
				 map.put("delSource","");
				cdDocFolderMapper.updateOrDelete(map);
				//日志
				super.invokeLogInsert( "400000000012", LogConstant.LOG_UPDATE, resUuid,"恢复文件");
			 }else{
				 repetitionFolderName=repetitionFolderName+cdDocFolderVos.get(0).getFolderName()+" ";
			 }
		}
	
		return repetitionFolderName;
	}
	/**
	 * 清空回收站
	 * @param createEmpNo 创建文件的EmpNo
	 */
	@Transactional
	public void emptyRecyCle(String createEmpNo){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("isDel", CommonConstant.COMMON_YES);
		map.put("createEmpNo",createEmpNo);
		cdDocFolderMapper.deleteIsDelCreateEmpNo(map);
		//日志
		super.invokeLogInsert( "400000000012", LogConstant.LOG_DELETE, createEmpNo,"清空回收站");

	}
	/**
	 * 删除文件 或者文件夹
	 * 通过uuid 或者 folderPath删除 folderPath需要模糊查询
	 * @param uuid 要删除的id
	 * @param userNo 创建的人
	 */
	@Transactional
	public void deleteFileUuid(String[] uuids,String userNo){
		Map<String, Object> map;
		for (String uuid:uuids) {
			map = new HashMap<String,Object>();
			map.put("uuid", uuid);
			map.put("folderPath", uuid);
			map.put("createEmpNo", userNo);
			map.put("isDel", CommonConstant.COMMON_YES);
			cdDocFolderMapper.deleteFileUuid(map);
			//日志
			super.invokeLogInsert( "400000000012", LogConstant.LOG_DELETE, uuid,"删除文件");
		}
	}
	
	
	
/*************************************文件上传*******************************************/
	@Transactional
	public String executeOnAfterFileUpload(FileBasicInfo basicInfo,
		Map<String, String> params) throws AppException {
		try{
			CdDocFolderVo cdDocFolderVo = new CdDocFolderVo();
			cdDocFolderVo.setUuid(basicInfo.getBusiId());
			cdDocFolderVo.setFolderType(CommonConstant.FILE);
			cdDocFolderVo.setFolderName(basicInfo.getCname());
			String parentId = params.get("parentId");
			cdDocFolderVo.setParentId(parentId);
			
			//通过父id查询上级目录的信息
			CdDocFolderVo pVo = getById(parentId);
			
			//通过parentId查询数据folderPath 和 folderPathName 并且加上当前的folderPath 和folderPathName
			if(pVo != null){ 
				if(!StringUtils.isEmpty(pVo.getFolderPath())){
					cdDocFolderVo.setFolderPath(pVo.getFolderPath()+","+pVo.getUuid());
					cdDocFolderVo.setFolderPathName(pVo.getFolderPathName()+","+pVo.getFolderName());
				}else{
					cdDocFolderVo.setFolderPath(pVo.getUuid());
					cdDocFolderVo.setFolderPathName(pVo.getFolderName());
				}
			}
			
			cdDocFolderVo.setRelatedId(basicInfo.getAttachId());
			
			cdDocFolderVo.setCreateDt(basicInfo.getCreateDt());
			cdDocFolderVo.setCreateEmp(basicInfo.getCreateEmp());
			cdDocFolderVo.setCreateEmpNo(basicInfo.getCreateEmpNo());
			cdDocFolderVo.setIsDel(basicInfo.getIsDel());
			String type = params.get("fileType");
			// cdDocFolderVo.setType(ShareConstant.File_TYPE_COMMON);
			cdDocFolderVo.setType(type);
			cdDocFolderMapper.insert(cdDocFolderVo);
			//日志
			super.invokeLogInsert( "400000000012", LogConstant.LOG_ADD, cdDocFolderVo.getUuid(),"上传文件");
			
		}catch(Exception e){
			logger.error("文件上传保存异常",e);
			throw new AppException("文件上传保存异常");
		}
		return null;
	}
	/**
	 *通过文件夹的uuid 修改文件夹的名字
	 * @param map
	 */
	@Transactional
	public void update(Map<String, Object> map){
		cdDocFolderMapper.update(map);
		
	}
	
	/**
	 * 通过项目id 删除数据
	 * @param uuid
	 */
	@Transactional
	public void deleteProjectDoc(Map<String, Object> map){
		cdDocFolderMapper.deleteProjectDoc(map);
	}
	/**
	 * 移动到公司文库
	 * @param uuid
	 * @throws AppException 
	 */
	@Transactional
	public void moveFrimLibrary(String uuid) throws AppException{
		//查询此项目是否完成
		ProjectVo projectVo = projectService.getById(uuid);
		if (!StringUtils.equals(projectVo.getStatus(), PmConstant.PRJ_STATUS_FLISH)) {
			throw new AppException("项目为结项 不能加入到公司文库");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", ShareConstant.File_TYPE_CORPORATION);
		map.put("uuid", uuid);
		cdDocFolderMapper.updateOrDelete(map);
	}
	
}
